<?php
class Mincoding_VendorConnect_Model_Resource_Contractproduct extends Mage_Core_Model_Resource_Db_Abstract
{
    protected function _construct()
    {
    	$this->_init("vendorconnect/contract", "");
    }
    
    /*
    @return array
    */
    public function getProductIdsSelected($contract_id=null)
    {
        $connectionRead = $this->_getReadAdapter();
        $table = $connectionRead->getTableName('mincoding_contract_product_flat');
        
        $select = $connectionRead->select()
            ->from($table, array('product_ids','contract_id'));  
        if ( strlen($contract_id) )
        {
            $select->where("contract_id = ?",$contract_id);    
        } 
        $row = $connectionRead->fetchRow($select);  
         
        if ( $row && isset($row['contract_id']) && $row['contract_id'] )
        {
            return explode(',',$row['product_ids']);    
        }
        return array();
    }
    
    public function checkContractProductExist($condition)
    {
        if ( $condition )
        {
            $connectionRead = $this->_getReadAdapter();
            $table = $connectionRead->getTableName('mincoding_contract_product');
            
            $select = $connectionRead->select()
                ->from($table, array('product_id','contract_id'));  
            $select->where($condition);
            
            $row = $connectionRead->fetchRow($select);  
             
            if ( $row && isset($row['contract_id']) && $row['contract_id'] )
            {
                return true;    
            }
            return false;     
        }   
        return -1; 
    }
    
    public function checkContractProductFlatExist($condition,$opt_result=0)
    {
        if ( $condition )
        {
            $connectionRead = $this->_getReadAdapter();
            $table = $connectionRead->getTableName('mincoding_contract_product_flat');
            
            $select = $connectionRead->select()
                ->from($table, array('product_ids','contract_id'));  
            $select->where($condition);
            
            $row = $connectionRead->fetchRow($select);  
            
            if ( $opt_result == 1 ) return $row;
             
            if ( $row && isset($row['contract_id']) && $row['contract_id'] )
            {
                return true;    
            }
            return false;     
        }   
        return -1; 
    }
    
    public function removeProducts($contractId=0,$removeByProductId=0)
    {
        $writeConnection = $this->_getWriteAdapter();
        $table = $writeConnection->getTableName('mincoding_contract_product');
        if (!$removeByProductId)
        {
            $query = "DELETE FROM `$table` WHERE contract_id='$contractId'";    
        }
        else if ($removeByProductId == 1 )
        {
            $query = "DELETE FROM `$table` WHERE product_id='$contractId'";    
        }
        else if ($removeByProductId == 2 )
        {
            $contractId = explode(',',$contractId);
            $productId = $contractId[0];
            $contractId = $contractId[1];
            $query = "DELETE FROM `$table` WHERE product_id='$productId' AND contract_id='$contractId'";
        }
        try {
            $writeConnection->query($query);
            return true;
        }
        catch(Exception $e)
        {
            return false;
        }
    }
    
    /*add new record to mincoding_contract_product*/
    public function addNewContractProduct($dateItem = array())
    {
        //$writeConnection = $this->_getWriteAdapter();
        $writeConnection = Mage::helper('vendorconnect')->getWriteConnection();
        $table = $writeConnection->getTableName('mincoding_contract_product');
        try
        {
            if ( $dateItem && isset($dateItem['contract_id']) && $dateItem['contract_id'] )
            {
                $writeConnection->beginTransaction();
                $fields = array(
                    'contract_id' => $dateItem['contract_id'],
                    'product_id' => $dateItem['product_id'],
                    'created_time' => $dateItem['created_time'],
                );
                $values = "'" . implode("','",$fields) . "'";
                $query = "INSERT INTO `$table`(contract_id,product_id,created_time) VALUES($values);";
                //echo $query, "<hr/>";
                $writeConnection->query($query);
                //$writeConnection->insert($table, $fields);    
                $writeConnection->commit();    
            }
        
            return true;
        }
        catch(Exception $e)
        {
            return false;
        }   
    }
    
    /*add new record to mincoding_contract_product*/
    public function addNewContractProductFlatProductAfterSave($dateItem = array(),$opt_act=0)
    {
        //$writeConnection = $this->_getWriteAdapter();
        $writeConnection = Mage::helper('vendorconnect')->getWriteConnection();
        $table = $writeConnection->getTableName('mincoding_contract_product_flat');
        try
        {
            //check record exits
            $contractId = $dateItem['contract_id'];
            $table = $writeConnection->getTableName('mincoding_contract_product_flat');
            $query = "SELECT `contract_id`,`product_ids` FROM `{$table}` WHERE contract_id='$contractId'";
            $row = $writeConnection->fetchRow($query);
            
            $writeConnection->beginTransaction();
            $fields = array(
                'contract_id' => $contractId,
                'product_id' => $dateItem['product_id'],
                'product_ids' => $dateItem['product_id'],
            ); 
//echo "<pre>"; var_dump($row);die;
            if ( $row && isset($row['contract_id']) && $row['contract_id'] )
            {
                $product_ids = $row['product_ids'];
                $productIds = explode(',',$product_ids);
                unset($fields['product_id']);
                if ( $product_ids && is_array($productIds) && $productIds && !in_array($dateItem['product_id'], $productIds) )
                {
                    //update product_ids field
                    $fields['product_ids'] = $product_ids . ',' . $dateItem['product_id'];
                    $fields['product_ids'] = trim($fields['product_ids'],',');
                    $where = $writeConnection->quoteInto('contract_id = ?', $contractId);
                    $writeConnection->update($table, $fields, $where);      
                }
                if ( !$product_ids )
                {
                    //blank value in this field
                    unset($fields['product_id']);
                    $fields['product_ids'] = $dateItem['product_id'];
                    $where = $writeConnection->quoteInto('contract_id = ?', $contractId);
                    $writeConnection->update($table, $fields, $where);    
                }
            }
            else 
            {
                
                $writeConnection->insert($table, $fields);  
            }
            
            $writeConnection->commit();
            
            return true;
        }
        catch(Exception $e)
        {
            return false;
        }   
    } 
    
    public function saveProducts($contractId=0,$productIds='')
    {
        if ( !$contractId ) return false;
        if ( !$this->removeProducts($contractId) ) return false;
        
        $writeConnection = $this->_getWriteAdapter();
        $table = $writeConnection->getTableName('mincoding_contract_product');
        
        try
        {
            if ( $productIds )
            {
                $writeConnection->beginTransaction();
                foreach ( explode(',',$productIds) as $productId )
                {
                    $fields = array(
                        'contract_id' => $contractId,
                        'product_id' => $productId,
                        'created_time' => date("Y-m-d H:i:s"),
                    );
                    $writeConnection->insert($table, $fields);    
                }
                $writeConnection->commit();    
            }
        
            //store to mincoding_contract_product_flat
            $table = $writeConnection->getTableName('mincoding_contract_product_flat');
            $query = "SELECT `contract_id` FROM `{$table}` WHERE contract_id='$contractId'";
            $row = $writeConnection->fetchRow($query);
            
            $writeConnection->beginTransaction();
            $fields = array(
                'contract_id' => $contractId,
                'product_ids' => $productIds,
            ); 
            if ( $row && isset($row['contract_id']) && $row['contract_id'] )
            {
                $where = $writeConnection->quoteInto('contract_id = ?', $row['contract_id']);
                $writeConnection->update($table, $fields, $where);        
            }
            else 
            {
                $writeConnection->insert($table, $fields);  
            }
            
            $writeConnection->commit();
            
            return true;
        }
        catch(Exception $e)
        {
            return false;
        }
        


    }    
}